import datetime
import json
import re

from django.contrib.auth import login, logout
from django.http import JsonResponse, HttpResponse

from django.views import View
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.user.models import User, UserHeadImage
from apps.user.serializers.user import UserInfoModelSerializer


# Create your views here.
class RegisterView(View):
    def post(self, request):
        json_data = request.POST
        mobile = json_data.get('mobile')
        smscode = json_data.get('smscode')
        password = json_data.get('password')
        password2 = json_data.get('password2')

        if not all([mobile, smscode, password, password2]):
            return HttpResponse(status.HTTP_400_BAD_REQUEST)

        if password != password2:
            return JsonResponse({'code': 401, 'errmsg': '两次输入密码不同'})

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', mobile):
            return JsonResponse({"code": 402, "errmsg": "手机号码不正确"})

        redis_cli = get_redis_connection('code')
        redis_sms_code = redis_cli.get('sms_%s' % mobile)
        if not redis_sms_code:
            return JsonResponse({'code': 403, 'errmsg': '验证码失效，请重试'})

        if smscode != redis_sms_code.decode():
            return JsonResponse({'code': 404, 'errmsg': '短信验证码错误'})

        user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        UserHeadImage.objects.create(user=user)
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        return response


class LogoutView(View):
    def delete(self, request):
        logout(request)
        ret = JsonResponse({'code': 0, 'errmsg': 'ok'})
        ret.delete_cookie('token')

        return ret


class UserHead(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        try:

            img_url = request.user.user_img.head_image.url
        except Exception as e:
            print(e)
            return JsonResponse({'code': 0, 'errmsg': 'error'})
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'img_url': img_url})


class UserInfo(APIView):
    permission_classes = [IsAuthenticated]

    def __init__(self):
        super().__init__()
        self.redis_conn = get_redis_connection('hobby')

    def get(self, request):
        userSerializer = UserInfoModelSerializer(request.user)

        hobby_list = []
        redis_list = self.redis_conn.lrange('hobby_%s' % request.user.id, 0, -1)
        for i in redis_list:
            hobby_list.append(i.decode())
        resp_dict = userSerializer.data
        resp_dict['hobby_list'] = hobby_list

        return Response(resp_dict)

    def put(self, request):

        json_data = json.loads(request.body)

        hobby_list = json_data.get('hobby_list')
        del json_data['hobby_list']

        signature = json_data.get('signature')
        username = json_data.get('username')

        if signature == '':
            json_data['signature'] = None
        if username == '':
            return Response({'code': 402, 'errmsg': "昵称不能为空"})

        birthday = json_data.get('birthday')
        y, m, d = birthday.split('-')
        if not all([y, m, d]):
            json_data['birthday'] = None
        else:
            json_data['birthday'] = datetime.date(year=int(y), month=int(m), day=int(d))

        userSerializer = UserInfoModelSerializer(data=json_data)

        try:
            userSerializer.is_valid(raise_exception=True)
        except Exception as e:
            print(e)
            return Response({'code': 401, 'errmsg': "修改失败"})

        userSerializer.update(request.user, json_data)

        pl = self.redis_conn.pipeline()
        pl.ltrim('hobby_%s' % request.user.id, 1, 0)
        for hobby in hobby_list:
            pl.lpush('hobby_%s' % request.user.id, hobby)
        pl.execute()

        return Response({'code': 0, 'errmsg': "ok"})


class HeadImg(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        image_data = request.FILES.get('file').read()

        from fdfs_client.client import Fdfs_client
        client = Fdfs_client('utils/fastdfs/client.conf')
        res = client.upload_by_buffer(image_data)
        if res['Status'] != 'Upload successed.':
            return Response({'code': 402, 'errmsg': '修改失败'})

        image_url = res['Remote file_id'].replace('\\', '/')
        try:
            user_head = UserHeadImage.objects.get(user=request.user)
            del_url = re.search(r'(group.*)', user_head.head_image.url).group(1)
            if user_head.head_image != 'group1/M00/00/03/wKhVg2DoawiAZrkgAAAk3Qbfmts6653819':
                client.delete_file(del_url)
            user_head.head_image = image_url
            user_head.save()
        except Exception as e:
            print(e)
            return Response({'code': 401, 'errmsg': '修改失败'})

        return Response({'code': 0, 'errmsg': 'ok'})
